fs = require 'fs'
url = require 'url'
path = require 'path'
less = require 'less'

LessPluginAutoPrefix = require('less-plugin-autoprefix')
autoprefix = new LessPluginAutoPrefix({browsers: [
  "ie >= 8"
  "ie_mob >= 10"
  "ff >= 26"
  "chrome >= 30"
  "safari >= 6"
  "opera >= 23"
  "ios >= 5"
  "android >= 2.3"
  "bb >= 10"
]})

#
# 响应单个on-the-fly less请求
#
module.exports = (root, options = {}) ->

  return (req, res, next) ->

    return next() unless req.method is 'GET' or req.method is 'HEAD'

    src = options.src

    fs.readFile src, (err, data) ->

      next(err) if err

      opts =
        paths: [root]
        filename: path.basename(src)
        plugins: [autoprefix]
      opts.compress = !!options.compress
      theme = new String(data)
      if req.query.theme!=undefined && req.query.theme!=''

        themetxt = req.query.theme.replace /\./g,''

        theme = new String(data).replace /variables/g,'variables.'+themetxt

      less.render theme, opts, (err, output) ->

        if err
          less.writeError(err) if options.debug
          res.status(500).send(err)
        else
          res.set('Content-Type', 'text/css').send(output.css)
